package controllers.api;

import models.logs.LoginToken;
import models.user.UserInfo;

import org.codehaus.jackson.JsonNode;

import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import utils.MengException;
import utils.StringUtils;

public class UserInfoController extends Controller {

	public static Result register() {

		JsonNode node = request().body().asJson();
		UserInfo ui = Json.fromJson(node, UserInfo.class);

		try {
			String username = UserInfo.getInstances().register(ui);
			return ok(StringUtils.toJson("username", username));
		} catch (MengException e) {
			e.printStackTrace();
			return ok(StringUtils.toJson(e));
		}
	}

	public static Result login() {

		JsonNode node = request().body().asJson();
		UserInfo ui = Json.fromJson(node, UserInfo.class);

		try {
			String username = UserInfo.getInstances().login(ui.username, ui.password);
			return ok(StringUtils.toJson("username", username));
		} catch (MengException e) {
			e.printStackTrace();
			return ok(StringUtils.toJson(e));
		}
	}
	
	public static Result getToken(String username){
		
		try {
			LoginToken lt = LoginToken.getInstances().getLoginToken(username);
			return ok(Json.toJson(lt));
		} catch (MengException e) {
			e.printStackTrace();
			return ok(StringUtils.toJson(e));
		}
	}
	
	public static Result logout(){
		String username = session().get("username");
		try {
			LoginToken.getInstances().destroyLoginToken(username);
			session().clear();
			return ok(StringUtils.returnSuccess());
		} catch (MengException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return ok(StringUtils.toJson(e));
		}
		
	}

	

}
